/**
 * 网络公共类
 * by dily
 * (c) copyright 2014 - 2035
 * All Rights Reserved. 
 * 存放网络公共方法 
 * 注意：是同步请求，不是异步
 */
module SocketManager {

    var sock;

    //连接服务器
    export function connectServer(host: string = "") {
        Global.waitPanel = new WaitPanel(1);
        GameConfig.gameScene().maskLayer.removeChildren();
        GameConfig.gameScene().maskLayer.addChild(Global.waitPanel);

        this.sock = io.connect(host);
        this.sock.on('m', this.onReceiveMessage, this);
        this.sock.on('connect', this.onSocketOpen, this);

        this.sock.connect(host);
    }

    //连接成功返回
    export function onSocketOpen(): void {
        GameConfig.gameScene().maskLayer.removeChild(Global.waitPanel);
        Global.waitPanel = null;
        lcp.LListener.getInstance().dispatchEvent(new lcp.LEvent('connect', this.id));
    }

    //消息返回后，会广播出去
    //Global.addEventListener("你发送的cmd名称",监听方法,this)
    export function onReceiveMessage(data): void {
        if (data.body) {
            data.body.is_me = data.body.source_id === this.id
        }
        console.log('receive', data)
        lcp.LListener.getInstance().dispatchEvent(new lcp.LEvent('game_msg', data, false));
    }

    //向服务端发送消息
    export function sendMessage(body): void {
        console.log('send', body)
        if (body.body) {
            body.body.source_id = this.sock.id
        } else {
            body.body = {
                source_id: this.sock.id
            }
        }
        this.sock.emit('m', body)
    }
}



